package com.kmzx.one.project.config.listener;

import com.kmzx.one.project.events.SelfAndUpEvent;
import com.kmzx.one.project.mapper.CustomerMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;


@Component("selfAndUpEventListener")
public class SelfAndUpEventListener {
    private static Logger logger = LoggerFactory.getLogger(SelfAndUpEventListener.class);

    @Autowired
    CustomerMapper customerMapper;
    @Async
    @EventListener(classes = {SelfAndUpEvent.class})
    @Transactional(rollbackFor = Exception.class)
    public void defaultSelfAndUpEvent(SelfAndUpEvent selfAndUpEvent) {

        String selfUserId = selfAndUpEvent.getSelfUserId();

        String upUserId = selfAndUpEvent.getUpUserId();


        String selfRankId = selfAndUpEvent.getSelfRankId();

        String upRankId = selfAndUpEvent.getUpRankId();

        if (selfRankId.equals(upRankId)) {
            Date now = new Date();
            logger.info("更新上下级关系:被邀请人:{},邀请人:{}", selfUserId, upUserId);
            int result = customerMapper.breakSelfAndUpRelations(selfUserId, upUserId, now);
            logger.info("更新上下级关系结果::被邀请人:{},邀请人:{},{}", selfUserId, upUserId, result);
        }

        BigDecimal selfRankMoney = selfAndUpEvent.getSelfRankMoney();
        BigDecimal growth = selfAndUpEvent.getUpRankMoney();
        if (selfRankMoney.compareTo(growth) >= 0) {
            Date now = new Date();
            logger.info("购买货仓---->更新上下级关系:被邀请人:{},邀请人:{}", selfUserId, upUserId);
            int result = customerMapper.breakSelfAndUpRelations(selfUserId, upUserId, now);
            logger.info("购买货仓---->更新上下级关系结果::被邀请人:{},邀请人:{},{}", selfUserId, upUserId, result);
        }

    }
}
